package com.banshuibao.bsb_android.download;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.adapter.VideoListViewAdapter;
import com.banshuibao.bsb_android.fragment.BaseFragment;
import com.banshuibao.bsb_android.model.DownloadInfo;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.bokecc.sdk.mobile.download.Downloader;

/**
 * 已下载标签页
 *
 * @author CC视频
 */
public class DownloadedFragment extends BaseFragment {

    private ListView downloadedListView;

    private List<DownloadInfo> pairs;

    private TextView menu;

    private VideoListViewAdapter videoListViewAdapter;

    private FragmentActivity activity;

    private DownloadedReceiver receiver;

    private boolean isCheckModel;

    private HashMap<String, String> deletes;

    private LinearLayout bottomLayout;

    private TextView all, delete;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = getActivity();
        receiver = new DownloadedReceiver();
        activity.registerReceiver(receiver, new IntentFilter(CCMediaConfig.ACTION_DOWNLOADED));
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return LayoutInflater.from(activity).inflate(R.layout.fragment_downloaded, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        downloadedListView = view.findViewById(R.id.listView);
        downloadedListView.setDivider(null);
        bottomLayout = view.findViewById(R.id.bottom_layout);
        all = view.findViewById(R.id.all);
        delete = view.findViewById(R.id.delete);
        menu = activity.findViewById(R.id.menu);
        menu.setOnClickListener(l);
        all.setOnClickListener(l);
        delete.setOnClickListener(l);
        downloadedListView.setOnItemClickListener(onItemClickListener);
        deletes = new HashMap<>();
        initData();
    }

    private View.OnClickListener l = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.all:
                    int listSize = videoListViewAdapter.getList().size();
                    if (listSize == 0)
                        return;
                    int deleteSize = deletes.size();
                    if (deleteSize >= listSize) {
                        for (int i = 0; i < listSize; ++i) {
                            videoListViewAdapter.getList().get(i).setCheck(false);
                        }
                        deletes.clear();
                    } else {
                        for (int i = 0; i < listSize; ++i) {
                            DownloadInfo downloadInfo = videoListViewAdapter.getList().get(i);
                            downloadInfo.setCheck(true);
                            deletes.put(downloadInfo.getTitle(), downloadInfo.getVideoId());
                        }
                    }
                    updateDeletesText();
                    videoListViewAdapter.notifyDataSetChanged();
                    break;
                case R.id.delete:
                    if (deletes.size() == 0) {
                        return;
                    }
                    for (HashMap.Entry<String, String> entry : deletes.entrySet()) {
                        delete(entry.getValue());
                    }
                    deletes.clear();
                    updateDeletesText();
                    videoListViewAdapter.notifyDataSetChanged();
                    break;
                case R.id.menu:
                    setCheckModel();
                    break;
            }
        }
    };

    private void updateDeletesText() {
        delete.setText(String.valueOf("删除" + "(" + deletes.size() + ")"));
    }

    private void initData() {
        pairs = new ArrayList<>();
        videoListViewAdapter = new VideoListViewAdapter(activity);
        downloadedListView.setAdapter(videoListViewAdapter);
        updateData();
    }

    private void updateData() {
        if (pairs != null)
            pairs.clear();
        else
            return;
        List<DownloadInfo> downloadInfos = DataSet.getDownloadInfos();
        for (DownloadInfo downloadInfo : downloadInfos) {

            if (downloadInfo.getStatus() != Downloader.FINISH) {
                continue;
            }
            pairs.add(downloadInfo);
        }
        videoListViewAdapter.setPairs(pairs);
    }

    public void setCheckModel() {
        if (isHidden())
            return;
        isCheckModel = !isCheckModel;
        if (isCheckModel) {
            bottomLayout.setVisibility(View.VISIBLE);
            menu.setText("取消");
        } else {
            menu.setText("管理");
            setClearDelete();
        }
        videoListViewAdapter.setShowCheck(isCheckModel);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            if (getActivity() != null) {
                menu = getActivity().findViewById(R.id.menu);
                menu.setOnClickListener(l);
            }
        }
        if (hidden) {
            setClearDelete();
        }
    }

    private void setClearDelete() {
        bottomLayout.setVisibility(View.GONE);
        menu.setText("管理");
        isCheckModel = false;
        int size = videoListViewAdapter.getList().size();
        for (int i = 0; i < size; ++i) {
            videoListViewAdapter.getList().get(i).setCheck(false);
        }
        deletes.clear();
        updateDeletesText();
        videoListViewAdapter.setShowCheck(isCheckModel);
    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @SuppressWarnings("unchecked")
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (videoListViewAdapter == null)
                return;
            DownloadInfo downloadInfo = videoListViewAdapter.getItem(position);
            if (isCheckModel) {
                downloadInfo.setCheck(!downloadInfo.isCheck());
                if (downloadInfo.isCheck())
                    deletes.put(downloadInfo.getTitle(), downloadInfo.getVideoId());
                else
                    deletes.remove(downloadInfo.getTitle());
                updateDeletesText();
                videoListViewAdapter.notifyDataSetChanged();
            } else {
                IntentManager.goMediaPlayActivity(getActivity(), downloadInfo.getVideoId(), downloadInfo.getShareUrl(), downloadInfo.getUuid(), downloadInfo.getImgUrl());
            }
        }
    };

    private void delete(String videoId) {
        DataSet.removeDownloadInfo(videoId);
        File file = MediaUtil.getMediaFile(CCMediaConfig.DOWNLOAD_DIR, videoId);
        if (file.exists()) {
            file.delete();
        }
        updateData();
        DataSet.saveData();
    }

    private class DownloadedReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            updateData();
            videoListViewAdapter.notifyDataSetChanged();
            downloadedListView.invalidate();
        }

    }

    @Override
    public void onDestroy() {
        activity.unregisterReceiver(receiver);
        if (videoListViewAdapter != null) {
            videoListViewAdapter.clear();
            videoListViewAdapter = null;
        }
        if (deletes != null) {
            deletes.clear();
            deletes = null;
        }
        super.onDestroy();
    }

}
